package server;

import java.io.IOException;

public class Mapper {
    private String appBase;
    private Host host;

    public Mapper(String appBase) {
        this.appBase = appBase;
    }

    public void init() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        host = new Host(appBase);
        host.init();
    }

    public void start() {
        host.start();
    }

    public void process(Request request, Response response) throws Exception {
        MappedData mappedData = getMappedDataFrom(request);

        host.process(request, response, mappedData);
    }

    private MappedData getMappedDataFrom(Request request) throws MappingException {
        String url = request.getUrl();
        String[] splits = url.split("/");
        if (splits.length < 3) {
            throw new MappingException();
        }
        MappedData mappedData = new MappedData();
        mappedData.setMappedContext(splits[1]);
        mappedData.setMappedUrlPattern("/" + splits[2]);
        return mappedData;
    }

}
